﻿using System;
using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace TSharp.Core.Aop.PolicyInjectionIntegrated
{
    /// <summary>
    /// 
    /// <para>2010/8/9</para>
    /// 	<para>THINKPADT61</para>
    /// 	<para>tangjingbo</para>
    /// </summary>
    public class ExtendedInterceptionElement : UnityContainerExtensionConfigurationElement
    {
        /// <summary>
        /// Gets the interceptor.
        /// </summary>
        /// <value>The interceptor.</value>
        [ConfigurationProperty("interceptor", IsRequired = false, DefaultValue = "")]
        public string Interceptor
        {
            get { return (string) this["interceptor"]; }
        }

        /// <summary>
        /// Execute this command against the given container.
        /// </summary>
        /// <param name="container">The <see cref="T:Microsoft.Practices.Unity.IUnityContainer"/> to configure.</param>
        /// <remarks>
        /// Interface implementors will implement this method to
        /// apply configuration changes to the container.</remarks>
        public override void Configure(IUnityContainer container)
        {
            base.Configure(container);
            var interception = new ExtendedInterception();
            if (!string.IsNullOrEmpty(Interceptor))
            {
                Type type = TypeResolver.ResolveType(Interceptor); // System.Type.GetType(this.Interceptor);
                if (null == type)
                {
                    throw new ConfigurationErrorsException(string.Format("The {0} is not a valid Interceptor.",
                                                                         Interceptor));
                }
                if (!typeof (IInterceptor).IsAssignableFrom(type))
                {
                    throw new ConfigurationErrorsException(string.Format("The {0} is not a valid Interceptor.",
                                                                         Interceptor));
                }
                interception.Interceptor = (IInterceptor) Activator.CreateInstance(type);
            }
            container.AddExtension(interception);
        }
    }
}